<?php namespace Phpcmf\Controllers\Admin;

class Order extends \Phpcmf\Table {

    public function __construct(...$params)
    {
        parent::__construct(...$params);


        \Phpcmf\Service::V()->assign([
            'menu' => \Phpcmf\Service::M('Auth')->_admin_menu(
                [
                    '订单管理' => [APP_DIR.'/'.\Phpcmf\Service::L('Router')->class.'/'.(\Phpcmf\Service::L('Router')->method == 'edit' ? 'index' : \Phpcmf\Service::L('Router')->method), 'fa fa-shopping-cart'],
                    '详情' => ['hide:'.APP_DIR.'/'.\Phpcmf\Service::L('Router')->class.'/edit', 'fa fa-edit'],
                ]
            ),
        ]);
    }

    public function add() {

        $id = (int)\Phpcmf\Service::L('Input')->get('id');
        $order = \Phpcmf\Service::M('Order', 'store')->info($id);
        if (!$order) {
            IS_AJAX_POST ? $this->_json(0, dr_lang('订单不存在')) : dr_store_order_html_error(dr_lang('订单不存在'));
        }

        $at = \Phpcmf\Service::L('Input')->get('at');
        \Phpcmf\Service::V()->assign([
            'order' => $order,
        ]);

        switch ($at) {

            case 'pay':
                // 订单付款
                if (IS_AJAX_POST) {
                    $order['pay_status'] == 1 && $this->_json(0, dr_lang('此订单已付款'));
                    if ($order['pay_status'] == 0) {
                        // 未付款，时后台为他付款
                        $note = \Phpcmf\Service::L('Input')->post('note');
                        !$note && $this->_json(0, dr_lang('备注信息必须填写'), ['field' => 'note']);
                        // 增加交易流水
                        $rt = \Phpcmf\Service::M('Pay')->add_paylog([
                            'uid' => $order['uid'],
                            'username' => $order['username'],
                            'touid' => 0,
                            'tousername' => '',
                            'mid' => 'my-store_buy-'.$order['id'],
                            'title' => dr_lang('订单编号：%s', $order['sn']),
                            'value' => -$order['money'],
                            'type' => 'admin',
                            'status' => 1,
                            'result' => $note,
                            'paytime' => SYS_TIME,
                            'inputtime' => SYS_TIME,
                        ]);
                        !$rt['code'] && $this->_json(0, $rt['msg']);
                        \Phpcmf\Service::M('Order', 'store')->pay($id, $rt['code'], 'admin');
                        $this->_json(1, dr_lang('操作成功'));
                    } else {
                        // 定金付款
                        $this->_json(0, dr_lang('未开放'));
                    }
                }
                break;

            case 'delivery':
                // 订单发货
                if (!$order['pay_status']) {
                    IS_AJAX_POST ? $this->_json(0, dr_lang('此订单还未付款')) : dr_store_order_html_error(dr_lang('此订单还未付款'));
                }
                $delivery_corp = \Phpcmf\Service::M('Order', 'store')->get_delivery_corp();
                if (IS_AJAX_POST) {
                    if ($order['deliver_status'] == 0) {
                        // 未发货，时后台为他发货
                        $data = \Phpcmf\Service::L('Input')->post('data');
                        !$data['note'] && $this->_json(0, dr_lang('备注信息必须填写'), ['field' => 'note']);
                        !$data['name'] && $this->_json(0, dr_lang('姓名必须填写'), ['field' => 'name']);
                        !$data['phone'] && $this->_json(0, dr_lang('电话号码必须填写'), ['field' => 'phone']);
                        !$data['address'] && $this->_json(0, dr_lang('详细地址必须填写'), ['field' => 'address']);
                        // 创建发货记录
                        $data['deliver_name'] = isset($delivery_corp[$data['id']]) ? $delivery_corp[$data['id']]['name'] : '';
                        $rt = \Phpcmf\Service::M('Order', 'store')->add_deliver_goods(0, $order, $data);
                        !$rt['code'] && $this->_json(0, $rt['msg']);
                        $this->_json(1, dr_lang('操作成功'));
                    } else {
                        // 定金付款
                        $this->_json(0, dr_lang('未开放'));
                    }
                }
                \Phpcmf\Service::V()->assign([
                    'delivery' => \Phpcmf\Service::M('Order', 'store')->deliver_info($order['deliver_id']),
                    'delivery_corp' => $delivery_corp,
                ]);
                break;

            case 'msg':
                // 短信通知
                if (IS_AJAX_POST) {
                    $note = \Phpcmf\Service::L('Input')->post('note');
                    !$note && $this->_json(0, dr_lang('信息内容必须填写'), ['field' => 'note']);
                    // 发送短信
                    $rt = $this->member_model->sendsms_text($order['phone'], $note);
                    !$rt['code'] && $this->_json(0, $rt['msg']);
                    $this->_json(1, dr_lang('操作成功'));
                }
                \Phpcmf\Service::V()->assign([
                    'message' => order_default_order_message(),
                ]);
                break;

            case 'receipt':
                // 收货
                if ($order['deliver_status'] != 1) {
                    IS_AJAX_POST ? $this->_json(0, dr_lang('此订单还未发货')) : dr_store_order_html_error(dr_lang('此订单还未发货'));
                }
                if (IS_AJAX_POST) {
                    $note = \Phpcmf\Service::L('Input')->post('note');
                    !$note && $this->_json(0, dr_lang('收货内容必须填写'), ['field' => 'note']);
                    // 签收订单
                    $rt = \Phpcmf\Service::M('Order', 'store')->receipt($order, $note);
                    $rt && !$rt['code'] && $this->_json(0, $rt['msg']);
                    $this->_json(1, dr_lang('操作成功'));
                }
                \Phpcmf\Service::V()->assign([
                    'delivery' => \Phpcmf\Service::M('Order', 'store')->deliver_info($order['deliver_id']),
                ]);
                break;

            case 'log':
                // 订单备注
                if (IS_AJAX_POST) {
                    $note = \Phpcmf\Service::L('Input')->post('note');
                    !$note && $this->_json(0, dr_lang('备注内容必须填写'), ['field' => 'note']);
                    // 订单备注
                    \Phpcmf\Service::M('Order', 'store')->add_log($order, $note);
                    $this->_json(1, dr_lang('操作成功'));
                }
                break;

            case 'close':
                // 订单关闭
                if ($order['status'] == 0) {
                    IS_AJAX_POST ? $this->_json(0, dr_lang('此订单已经关闭')) : dr_store_order_html_error(dr_lang('此订单已经关闭'));
                } elseif ($order['status'] == 9) {
                    IS_AJAX_POST ? $this->_json(0, dr_lang('此订单已经交易完成')) : dr_store_order_html_error(dr_lang('此订单已经交易完成'));
                }

                if (IS_AJAX_POST) {
                    $note = \Phpcmf\Service::L('Input')->post('note');
                    !$note && $this->_json(0, dr_lang('关闭原因必须填写'), ['field' => 'note']);
                    $order['deliver_status'] == 1 && (IS_AJAX_POST ? $this->_json(0, dr_lang('此订单已经发货，无法关闭')) : dr_store_order_html_error(dr_lang('此订单已经发货，无法关闭')));
                    // 订单备注
                    \Phpcmf\Service::M('Order', 'store')->close($order, $note);
                    // 判断是否付款
                    if ($order['status'] == 2 && $order['money'] > 0) {
                        // 退款到用户
                        \Phpcmf\Service::M('member')->add_money($order['uid'], $order['money']);
                        \Phpcmf\Service::M('Pay')->add_paylog([
                            'uid' => $order['uid'],
                            'username' => $order['username'],
                            'touid' => 0,
                            'tousername' => '',
                            'mid' => 'order',
                            'title' => dr_lang('订单%s退款', $order['sn']),
                            'value' => $order['money'],
                            'type' => 'admin',
                            'status' => 1,
                            'url' => '',
                            'result' => $order['sn'],
                            'paytime' => SYS_TIME,
                            'inputtime' => SYS_TIME,
                        ]);
                    }
                    $this->_json(1, dr_lang('操作成功'));
                }

                break;

        }
        \Phpcmf\Service::V()->display('api_'.$at.'.html');exit;
    }

    public function edit() {

        // 表单显示名称
        $this->name = dr_lang('订单');
        $this->is_list_data = 0;

        // 初始化数据表
        $this->_init(['table' => SITE_ID.'_store_order']);

        $id = (int)\Phpcmf\Service::L('Input')->get('id');
        list($tpl, $data) = $this->_Show($id);
        !$data && $this->_admin_msg(0, dr_lang('订单不存在'));

        \Phpcmf\Service::V()->assign([
            'order' => $data,
            'goods' => \Phpcmf\Service::M('Order', 'store')->goods($id),
            'comment' => \Phpcmf\Service::M('Order', 'store')->comment($data['mid'], $id),
            'review' => $this->get_cache('module-'.SITE_ID.'-store', 'comment', 'review'),
            'op_log' => \Phpcmf\Service::M('Order', 'store')->log($id),
            'op_url' => \Phpcmf\Service::L('Router')->url(APP_DIR.'/order/add', ['id' => $id]),
        ]);
        \Phpcmf\Service::V()->display('order_show.html');
    }


    private function _list_data() {

        // 模板前缀(避免混淆)
        $this->my_field = array(
            'sn' => array(
                'ismain' => 1,
                'name' => dr_lang('订单编号'),
                'fieldname' => 'sn',
                'fieldtype' => 'Text',
            ),
            'id' => array(
                'ismain' => 1,
                'name' => dr_lang('订单ID'),
                'fieldname' => 'id',
                'fieldtype' => 'Text',
            ),
            'name' => array(
                'ismain' => 1,
                'name' => dr_lang('收货人'),
                'fieldname' => 'name',
                'fieldtype' => 'Text',
            ),
            'phone' => array(
                'ismain' => 1,
                'name' => dr_lang('电话'),
                'fieldname' => 'phone',
                'fieldtype' => 'Text',
            ),
            'email' => array(
                'ismain' => 1,
                'name' => dr_lang('邮箱'),
                'fieldname' => 'email',
                'fieldtype' => 'Text',
            ),
            'address' => array(
                'ismain' => 1,
                'name' => dr_lang('地址'),
                'fieldname' => 'address',
                'fieldtype' => 'Text',
            ),
            'remark' => array(
                'ismain' => 1,
                'name' => dr_lang('备注'),
                'fieldname' => 'remark',
                'fieldtype' => 'Text',
            ),
            'username' => array(
                'ismain' => 1,
                'name' => dr_lang('账户'),
                'fieldname' => 'username',
                'fieldtype' => 'Text',
            ),
            'uid' => array(
                'ismain' => 1,
                'name' => dr_lang('uid'),
                'fieldname' => 'uid',
                'fieldtype' => 'Text',
            ),
        );

        // 表单显示名称
        $this->name = dr_lang('订单');

        // 控制器筛选
        switch (\Phpcmf\Service::L('Router')->method) {
            case 'index':
                // 最新订单 3天内的
                $where = ' `inputtime` between '.strtotime("-3 day").' and '.SYS_TIME;
                break;
            case 'st2_index':
                $where = ' `status` = 2 and `deliver_status` = 0';
                break;
            default:
                $where = ' `status` = '.intval(substr(\Phpcmf\Service::L('Router')->method, 2, 1));
                break;
        }

        // 初始化数据表
        $this->_init([
            'table' => SITE_ID.'_store_order',
            'field' => $this->my_field,
            'sys_field' => [],
            'order_by' => 'inputtime desc',
            'date_field' => 'inputtime',
            'list_field' => [],
            'where_list' => $where,
        ]);
        list($a, $data) = $this->_List();

        $list = [];
        foreach ($data['list'] as $t) {
            $t['goods'] = \Phpcmf\Service::M('Order', 'store')->goods($t['id']);
            $list[] = $t;
        }

        \Phpcmf\Service::V()->assign([
            'list' => $list,
            'field' => $this->my_field,
        ]);
        \Phpcmf\Service::V()->display('order_list.html');
    }

    public function index() {
        $this->_list_data();
    }

    public function st0_index() {
        $this->_list_data();
    }

    public function st1_index() {
        $this->_list_data();
    }

    public function st2_index() {
        $this->_list_data();
    }

    public function st3_index() {
        $this->_list_data();
    }

    public function st4_index() {
        $this->_list_data();
    }

    public function st5_index() {
        $this->_list_data();
    }

    public function st6_index() {
        $this->_list_data();
    }

    public function st7_index() {
        $this->_list_data();
    }

    public function st8_index() {
        $this->_list_data();
    }

    public function st9_index() {
        $this->_list_data();
    }

    // 后台删除
    public function del() {

        // 删除时同步删除很多内容
        // 初始化数据表
        $this->_init(['table' => SITE_ID.'_store_order']);
        $this->_Del(
            \Phpcmf\Service::L('input')->get_post_ids(),
            null,
            function ($rows) {
                $ids = [];
                foreach ($rows as $t) {
                    $ids[] = $id = intval($t['id']);
                    \Phpcmf\Service::M()->table_site('store_order_log')->where('oid', $id)->delete();
                    \Phpcmf\Service::M()->table_site('store_order_goods')->where('oid', $id)->delete();
                    \Phpcmf\Service::M()->table_site('store_order_service')->where('oid', $id)->delete();
                    \Phpcmf\Service::M()->table_site('store_order_deliver_goods')->where('oid', $id)->delete();

                }
                return dr_return_data(1, 'ok');
            },
            \Phpcmf\Service::M()->dbprefix('member')
        );
    }

}
